package com.cfks.lanscript;

import java.util.*;
import java.io.*;

public class Main {
  public static void main(String[] args) {
    try {
      if (args[0].equals("lsc")) {
        // 编译
        long startTime = System.currentTimeMillis();
        String result = LanScriptCompiler.compile(readString(new File(args[1])));
        File file = new File(args[1]);
        String savePath = args[1].replace(file.getName(), "") + getFilePrefix(file) + ".lsc";
        write(new File(savePath), result);
        long endTime = System.currentTimeMillis();
        System.out.println(
            String.format(
                "Compile successfully! Takes %s ms. Save path: %s",
                Long.toString((endTime - startTime)), savePath));
      } else if (args[0].equals("lsr")) {
        // 运行
        long startTime = System.currentTimeMillis();
        LanScriptRunner.run(readString(new File(args[1])));
        long endTime = System.currentTimeMillis();
        System.out.println(
            String.format(
                "Running successfully! Takes %s ms.", Long.toString((endTime - startTime))));
      }
    } catch (Exception e) {
      e.printStackTrace();
      LanScriptRunner.log("Error: " + e.toString());
    }
  }

  private static String readString(File file) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    boolean first = true;
    StringBuilder content = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
      if (first) {
        first = false;
        content.append(line);
      } else {
        content.append('\n').append(line);
      }
    }
    br.close();
    return content.toString();
  }

  private static String getFilePrefix(File f) {
    if (f == null) {
      return null;
    }
    String name = f.getName();
    int i = name.lastIndexOf('.');
    if (i == -1) {
      return name;
    } else {
      return name.substring(0, i);
    }
  }

  private static void write(File file, String content) throws IOException {
    if (!file.exists()) {
      createFile(file);
    }
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
    writer.write(content);
    writer.flush();
    writer.close();
  }

  private static boolean createFile(File file) {
    try {
      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }
      return file.createNewFile();
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }
}
